﻿using System;
using System.Windows.Browser;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using SBPweb.RIA.Client.Common.Patterns;

using SBPweb.RIA.Client.Contracts.Base;
using SBPweb.RIA.Client.Contracts.Models;

using SBPweb.RIA.Client.Controls.Base;

namespace SBPweb.RIA.Client.Controls.Models
{

    public class DOMContextModel : DependencyObjectBase, IDOMContextModel
    {

        #region Fields

        private static SingletonHelper<DOMContextModel> sh = new SingletonHelper<DOMContextModel>();
        private KeyedCollection<string, IPluginContainerModel> pluginContainers = new PluginContainerModelCollection();

        #endregion

        #region Constructor logic

        public DOMContextModel()
        {
            if (ExtendableApplication.Current == null || ExtendableApplication.Current.IsRunningOutOfBrowser || ExtendableApplication.Current.IsDesignTime)
            {
                return;
            }

            Screen = new ScreenModel();
            PluginContainer = new PluginContainerModel(HtmlPage.Plugin.Parent);
            PluginContainer.MainVisual = ExtendableApplication.Current.RootVisual;

            pluginContainers.Add(PluginContainer);

            IsAvailable = true;
        }

        #endregion

        #region Properties

        public static IDOMContextModel SingletonInstance
        {
            get
            {
                return sh.Instance;
            }
        }

        public bool IsAvailable
        {
            get;
            private set;
        }
        
        public IScreenModel Screen
        {
            get;
            private set;
        }

        public IPluginContainerModel PluginContainer
        {
            get;
            private set;
        }
        
        #endregion

        #region Methods

        public IPluginContainerModel GetModel(string containerId)
        {
            if (pluginContainers.Contains(containerId))
            {
                return pluginContainers[containerId];
            }
            PluginContainerModel ret = new PluginContainerModel(containerId);
            pluginContainers.Add(ret);
            return ret;
        }

        public void RegisterScriptableModel(string name, IScriptableModel model)
        {
            HtmlPage.RegisterScriptableObject(name, model);
        }
        
        #endregion

    }

}